﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace WebTranslator {
	public class Baza {
		static List<User> L = new List<User>();
		static string fname = "users.users";
		public static void start() {
			if (File.Exists(fname) == false) Zapisz();
			Wczytaj();
		}

		public static bool Logowanie(string name, string pass) {
			User u = new User();
			u.name = name;
			if (JestUser(name))
				return L[L.IndexOf(u)].haslo == pass;
			else return false;
		}

		public static bool JestUser(string name) {
			foreach (User u in L) if (u.name == name) return true;
			return false;
		}

		public static int DodajUser(string name, string pass) {
			try {
				User u = new User();
				u.name = name;
				u.haslo = pass;
				L.Add(u);
				Zapisz();
			} catch (Exception) { return 0; }
			return 1;
		}

		static void wyp() {
			foreach (User s in L) Console.WriteLine(s.name + " " + s.pkt);
		}

		public static bool UsunUser(string name) {
			User u = new User();
			u.name = name;
			bool p = L.Remove(u);
			Zapisz();
			return p;
		}

		static void Zapisz() {
			if (File.Exists(fname)) File.Delete(fname);
			FileStream f = File.OpenWrite(fname);
			Stream sw = f as Stream;
			BinaryFormatter b = new BinaryFormatter();
			b.Serialize(sw, L);
			sw.Close();
		}

		static void Wczytaj() {
			FileStream f = File.OpenRead(fname);
			Stream sw = f as Stream;
			BinaryFormatter b = new BinaryFormatter();
			L = b.Deserialize(f) as List<User>;
			sw.Close();
		}

		public static int IlePkt(string name) {
			User u = new User();
			u.name = name;
			return L[L.IndexOf(u)].pkt;
		}

		public static void DodajPkt(string name, string pkt) {
			User u = new User();
			u.name = name;
            int wyn = Int32.Parse(pkt);
			L[L.IndexOf(u)].pkt += wyn;
			// s.pkt += pkt;
			Zapisz();
		}
	}

	[Serializable]
	public class User {
		public string name;
		public string haslo;
		public int pkt = 0;

		public override int GetHashCode() {
			return base.GetHashCode();
		}

		public override bool Equals(object obj) {
			return (obj as User).name == this.name;
		}
	}
}
